package com.qzsoft.zhjd.materiel.modules.materielapi.aop;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.qzsoft.zhjd.materiel.modules.materielapi.service.MaterielApiVesionService;

/**
 * @ClassName ClientApiAspect
 * @Description 客户端接口切面
 * @author linhuawei
 * @since 2021-12-11
 */
@Aspect
@Component
public class MaterielApiAspect {

    @Autowired
    private MaterielApiVesionService materielApiVesionService;

    @Pointcut("@annotation(com.qzsoft.zhjd.materiel.modules.materielapi.aop.MaterielApi)")
    public void pointCut() {
    }

    @Around("pointCut() && @annotation(materielApi)")
    public Object doAround(ProceedingJoinPoint point, MaterielApi materielApi) throws Throwable {
        // 获取注解内容，获取当前接口版本号
        String code = materielApi.value();
        Long lastVersion = materielApiVesionService.getVersionByCode(code);

        // 获取当前传递的版本号
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getRequest();
        String versionStr = request.getHeader("version");
        Long version = 0L;
        if (ObjectUtils.isNotEmpty(versionStr)) {
            try {
                version = Long.parseLong(versionStr);
            } catch (Exception e) {
                version = -0L;
            }
        }

        // 如果最新版本号小于传递的版本号，返回无需更新数据内容
        // 否则继续执行，并在返回结果中添加版本字段
        ExtResult result;
        if (version >= lastVersion) {
            result = ExtResult.ingnore();
        } else {
            Object[] args = point.getArgs();
            result = (ExtResult) point.proceed(args);
        }
        result.setVersion(lastVersion);
        return result;
    }

}
